var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var path = require('path');
var del = require('del');
var { exec } = require('child_process');

var distPath = path.resolve('./dist');
var version = ''; // 版本号
var versionPath = ''; // 版本号路径
var env = ''; // 运行环境

// 创建版本号(年月日时分)
(function () {
  var d = new Date();
  var yy = d.getFullYear().toString().slice(2);
  var MM = d.getMonth() + 1 >= 10 ? (d.getMonth() + 1) : '0' + (d.getMonth() + 1);
  var DD = d.getDate() >= 10 ? d.getDate() : '0' + d.getDate();
  var h = d.getHours() >= 10 ? d.getHours() : '0' + d.getHours();
  var mm = d.getMinutes() >= 10 ? d.getMinutes() : '0' + d.getMinutes();
  version = yy + MM + DD + h + mm;
  versionPath = path.join(distPath, version);
  console.log('Version:', version); // 添加日志记录
  console.log('Version Path:', versionPath); // 添加日志记录
})();

console.log('build开始'); // 添加日志记录

// 编译
gulp.task('build', function(done) {
  console.log('Starting build task...'); // 添加日志记录
  process.env.ASSETS_PUBLIC_PATH = `/${version}/`; // 设置环境变量
  console.log('ASSETS_PUBLIC_PATH:', process.env.ASSETS_PUBLIC_PATH); // 添加日志记录
  exec('node build/build.js', (err, stdout, stderr) => {
    if (err) {
      console.error('Build failed:', err);
      done(err);
      return;
    }
    console.log(stdout);
    console.error(stderr);
    done();
  });
});

console.log('创建版本号目录'); // 添加日志记录

// 创建版本号目录
gulp.task('create:versionCatalog', function () {
  console.log('Starting create:versionCatalog task...'); // 添加日志记录
  return gulp.src(`${distPath}/**/*`)
    .pipe(gulp.dest(`${versionPath}/`))
    .on('end', () => {
      console.log('create:versionCatalog task completed.'); // 添加日志记录
    });
});

console.log('开始替换CDN'); // 添加日志记录

// 替换${versionPath}/static/js/manifest.js window.SITE_CONFIG.cdnUrl占位变量
gulp.task('replace:cdnUrl', gulp.series('create:versionCatalog', function () {
  console.log('Starting replace:cdnUrl task...'); // 添加日志记录
  return gulp.src(`${versionPath}/static/js/manifest.js`)
    .pipe($.replace(new RegExp(`"${require('./config').build.assetsPublicPath}"`, 'g'), `window.SITE_CONFIG.cdnUrl + "/"`))
    .pipe(gulp.dest(`${versionPath}/static/js/`))
    .on('end', () => {
      console.log('replace:cdnUrl task completed.'); // 添加日志记录
    });
}));

// 替换${versionPath}/static/config/index-${env}.js window.SITE_CONFIG['version']配置变量
gulp.task('replace:version', gulp.series('create:versionCatalog', function () {
  console.log('Starting replace:version task...'); // 添加日志记录
  return gulp.src(`${versionPath}/static/config/index-${env}.js`)
    .pipe($.replace(/window.SITE_CONFIG\['version'\] = '.*'/g, `window.SITE_CONFIG['version'] = '${version}'`))
    .pipe(gulp.dest(`${versionPath}/static/config/`))
    .on('end', () => {
      console.log('replace:version task completed.'); // 添加日志记录
    });
}));

// 合并${versionPath}/static/config/[index-${env}, init].js 至 ${distPath}/config/index.js
gulp.task('concat:config', gulp.series('replace:version', function () {
  console.log('Starting concat:config task...'); // 添加日志记录
  return gulp.src([`${versionPath}/static/config/index-${env}.js`, `${versionPath}/static/config/init.js`])
    .pipe($.concat('index.js'))
    .pipe(gulp.dest(`${distPath}/config/`))
    .on('end', () => {
      console.log('concat:config task completed.'); // 添加日志记录
    });
}));

// 清空
gulp.task('clean', function () {
  console.log('Starting clean task...'); // 添加日志记录
  return del([versionPath]);
});

// 默认任务
gulp.task('default', gulp.series(
  'clean',
  function (done) {
    // 获取环境配置
    env = process.env.npm_config_qa ? 'qa' : process.env.npm_config_uat ? 'uat' : 'prod';
    console.log('Environment:', env); // 添加日志记录
    done(); // 确保异步任务完成
  },
  'build',
  'create:versionCatalog',
  'replace:cdnUrl',
  'replace:version',
  'concat:config',
  function () {
    // 清除, 编译 / 处理项目中产生的文件
    return del([`${distPath}/static`, `${versionPath}/static/config`]).then(() => {
      console.log('Build completed successfully.'); // 添加日志记录
    });
  }
));